# -*- coding: utf-8 -*-

from blog.models import *
from blog.forms import *

from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.contrib.auth.decorators import login_required
from django.template.defaultfilters import slugify
from session_messages import create_message
from django.views.generic.list_detail import object_list
from django.contrib.auth.models import User
from django.db.models import Q

import datetime

def posty(request, glowny, template_name='blog/index.html'):
    if glowny:
        news = News.objects.filter( Q( czyNaGlowny = True)).order_by('-dataDodania')
    else:
	news = News.objects.all().order_by('-dataDodania')
    return object_list(request, news, paginate_by=4, allow_empty=True, template_name = template_name)
    
def posty_kategoria(request, slug, template_name='blog/index.html'):
    news = News.objects.filter( Q( kategoria__slug = slug)).order_by('-dataDodania')
    return object_list(request, news, paginate_by=4, allow_empty=True, template_name = template_name)
    
def posty_tag(request, slug, template_name='blog/index.html'):
    news = News.objects.filter( Q(  tagi__slug = slug)).order_by('-dataDodania')
    return object_list(request, news, paginate_by=4, allow_empty=True, template_name = template_name)

def posty_archiwum(request, month=None, year=None, template_name='blog/index.html'):
    news = News.objects.filter(Q(dataDodania__year=int(year), dataDodania__month= int(month)))
    return object_list(request, news, paginate_by=4, allow_empty=True, template_name = template_name)

def posty_najstarsze(request, template_name='blog/index.html'):
    date =  datetime.datetime.now().date() - datetime.timedelta(days=90)
    news = News.objects.filter(Q(dataDodania__lt = date))
    return object_list(request, news, paginate_by=4, allow_empty=True, template_name = template_name)
	

def post(request, autor, rok, miesiac, slug, template_name="blog/post.html"):
    news = News.objects.filter(slug=slug, dataDodania__year=int(rok), dataDodania__month= int(miesiac)).filter( autor__username = autor)
    news = news[0]
    komentarze = news.komentarze.all().order_by('-dataDodania')
    ostatnie_posty =  News.objects.filter( Q(  autor = news.autor)).order_by('-dataDodania')[:3]
    paginator = Paginator(komentarze, 10)    
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        komentarze = paginator.page(page)
    except (EmptyPage, InvalidPage):
        komentarze = paginator.page(paginator.num_pages)
    form = komentarzForm()
    if request.method == "POST":
        form = komentarzForm(request.POST)
        if form.is_valid():
            nowy_komentarz = form.save(commit = False)
            nowy_komentarz.dataDodania = datetime.datetime.now()
	    nowy_komentarz.autor = request.user
            nowy_komentarz.save()
            news.komentarze.add(nowy_komentarz)
            news.save()
            return HttpResponseRedirect(news.get_absolute_url())
    return render_to_response(template_name, RequestContext(request,  {"post": news,"komentarze":komentarze, "form":form, "ostatnie_posty":ostatnie_posty}))

def post_usun(request, id):
    news = get_object_or_404(News, id = id)
    if news.autor == request.user:
	news.delete()
	create_message(request, u'Post został pomyślnie usuniety')
	return HttpResponseRedirect('/blog')
    else:
	create_message(request, u'Nie masz prawa')
        return HttpResponseRedirect('/blog')

def post_edytuj(request, id, template_name="blog/post-dodaj.html"):
    news = get_object_or_404(News, id = id)
    if not news.autor == request.user:
	create_message(request, u'Nie masz prawa')
        return HttpResponseRedirect('/blog')
    if request.method == "POST":
	form = newsForm(request.POST, instance=news)
	if form.is_valid():
	    form.save(commit = False)
            news.dataEdycji = datetime.datetime.now()
            news.slug = slugify(news.tytul)
	    news.iloscEdycji += 1
            news.save()   
            form.save_m2m() 
	    noweTagi = request.POST['noweTagi']
	    if noweTagi:
	        noweTagi = noweTagi.split(',')
	        for tag in noweTagi:
		    tag = tag.strip()
		    nowy_tag = Tag()
		    nowy_tag.nazwa = tag
		    nowy_tag.slug = slugify(tag)
		    nowy_tag.save()
	   	    news.tagi.add(nowy_tag)            
            return HttpResponseRedirect(news.get_absolute_url())
    else:
	form = newsForm(instance=news)
    return render_to_response(template_name, RequestContext(request, { "form":form }))

def post_dodaj(request, template_name='blog/post-dodaj.html'):
    form = newsForm()    
    if request.method == "POST":
	form = newsForm(request.POST)
	if form.is_valid():
	    nowy_post = form.save(commit = False)
	    nowy_post.autor = request.user
            nowy_post.dataDodania = datetime.datetime.now()
            nowy_post.slug = slugify(nowy_post.tytul)
            nowy_post.save()   
            form.save_m2m() 
	    noweTagi = request.POST['noweTagi']
	    if noweTagi:
	        noweTagi = noweTagi.split(',')
	        for tag in noweTagi:
		    tag = tag.strip()
		    nowy_tag = Tag()
		    nowy_tag.nazwa = tag
		    nowy_tag.slug = slugify(tag)
		    nowy_tag.save()
	   	    nowy_post.tagi.add(nowy_tag)            
	    return HttpResponseRedirect(nowy_post.get_absolute_url())
    return render_to_response(template_name, RequestContext(request, {"form":form}))




	
